<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { getCategoryPage } from '@/api/product/permission'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  reqAddCategory,
  reqUpdateCategory,
  reqDeleteCategory,
} from '@/api/product/permission'
//新增说明说明分类的控制按钮
let foodOrOther = ref<string>('1')
//分类窗口是否显示
let dialogFormVisible = ref<boolean>(false)
//当前页码
let pageNo = ref<number>(1)
//每页条数
let limit = ref<number>(10)
// 存储一下已有品牌数据的总数
let total = ref<number>(0)
//存储数据
let dishArr = ref<any>([])
//分类数据
let categoryParams = reactive<any>({
  id: '',
  type: '1', //2
  name: '',
  sort: '',
  createTime: '',
  updateTime: '',
  createUser: '',
  updateUser: '',
})
// 获取已有品牌的接口封装为一个函数
const getDish = async () => {
  let result = await getCategoryPage(pageNo.value, limit.value)
  console.log(result)
  if (result.code == 1) {
    //存储总个数
    total.value = result.data.total
    dishArr.value = result.data.records
  }
}
//分页器页码发生变化时候触发
const changePageNo = () => {
  //当前页码发生变化的时候，再次发请求，获取数据
  getDish()
}
//当下拉菜单发生变化的时候，会触发此方法
const sizeChange = () => {
  pageNo.value = 1
  getDish()
}
//发送请求，组件一挂载
onMounted(() => {
  getDish()
})
//新增菜品分类
const addFoodCategory = () => {
  categoryParams.id = ''
  categoryParams.type = '1' //2
  categoryParams.name = ''
  categoryParams.sort = ''
  categoryParams.createTime = ''
  categoryParams.updateTime = ''
  categoryParams.createUser = ''
  categoryParams.updateUser = ''
  foodOrOther.value = '1'
  dialogFormVisible.value = true
}
//新增套餐分类
const addOtherCategory = () => {
  categoryParams.id = ''
  categoryParams.type = '2' //2
  categoryParams.name = ''
  categoryParams.sort = ''
  categoryParams.createTime = ''
  categoryParams.updateTime = ''
  categoryParams.createUser = ''
  categoryParams.updateUser = ''
  foodOrOther.value = '2'
  dialogFormVisible.value = true
}
//点击确定
const confirm = async () => {
  if (categoryParams.createUser == null) {
    categoryParams.createUser = localStorage.getItem('token')
  }
  categoryParams.updateUser = localStorage.getItem('token')
  // 判断是否是新增还是 修改
  if (categoryParams.updateTime == '') {
    categoryParams.type = foodOrOther
    console.log('add category')
    let result = await reqAddCategory(categoryParams)
    if (result.code == 1) {
      //添加用户成功
      dialogFormVisible.value = false
      //弹出提示
      ElMessage({
        type: 'success',
        message: '添加分类成功',
      })
      //发起请求
      getDish()
      //收集数据清空
    } else {
      //失败
      ElMessage({
        type: 'error',
        message: '添加分类失败',
      })
      dialogFormVisible.value = false
    }
  } else {
    console.log('update category')
    let result = await reqUpdateCategory(categoryParams)
    if (result.code == 1) {
      //添加用户成功
      dialogFormVisible.value = false
      //弹出提示
      ElMessage({
        type: 'success',
        message: '更新分类成功',
      })
      //发起请求
      getDish()
    } else {
      //失败
      ElMessage({
        type: 'error',
        message: '更新分类失败',
      })
      dialogFormVisible.value = false
    }
  }
}
//表单校验规则对象
//required:必须校验, brigger: 出发校验时机
const rules = {
  name: [{ required: true, trigger: 'blur' }],
  sort: [{ required: true, trigger: 'blur' }],
}
//是否删除的弹出确定框
const open = (row: any) => {
  let message = '是否删除'
  ElMessageBox.alert(message, row.name, {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: '确定',
    callback: (action: Action) => {
      if (action == 'cancel') {
        ElMessage({
          type: 'info',
          message: '取消',
        })
      } else {
        //调用修改状态的方法
        deleteCategory(row)
      }
    },
  })
}
//删除方法
const deleteCategory = async (row: any) => {
  console.log('del category')
  let result = await reqDeleteCategory(row.id)
  if (result.code == 1) {
    //弹出提示
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //发起请求
    getDish()
  } else {
    //失败
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
//编辑方法
const edit = (row: any) => {
  //ES6合并对象
  Object.assign(categoryParams, row)
  dialogFormVisible.value = true
}
</script>

<template>
  <div class="-container">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- card body -->
      <!-- 顶部的设置按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addFoodCategory"
      >
        添加菜品分类
      </el-button>
      <el-button
        type="info"
        size="default"
        icon="Plus"
        @click="addOtherCategory"
      >
        添加套餐分类
      </el-button>
      <!-- 表格组件用户展示已经有的菜品 -->
      <el-table :data="dishArr" style="margin: 20px 0px">
        <el-table-column label="分类名称" prop="name"></el-table-column>
        <el-table-column label="分类类型" width="100">
          <template #="{ row, $index }">
            <text>{{ row.type == 1 ? '菜品分类' : '套餐分类' }}</text>
          </template>
        </el-table-column>
        <el-table-column label="最后操作时间">
          <template #="{ row, $index }">
            <text style="color: rgb(108, 200, 239)">{{ row.updateTime }}</text>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort"></el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              circle
              @click="edit(row)"
            />
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              circle
              @click="open(row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件
       v-model:current-page :设置当前的分页器页码
       v-model:page-size : 展示条数每一页
       :page-sizes :设置下拉框的选择条数
       layout ：分页器的六个子组件的位置调整
      -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="changePageNo"
      />
    </el-card>
    <!-- 套餐新增按钮的弹出框 -->
    <el-dialog
      :title="foodOrOther == '1' ? '菜品分类' : '套餐分类'"
      v-model="dialogFormVisible"
    >
      <el-form
        :inline="false"
        size="normal"
        label-width="20%"
        :model="categoryParams"
        :rules="rules"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryParams.name"
            placeholder="输入名称"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model="categoryParams.sort"
            placeholder="输入排序"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <el-button
          type="primary"
          size="default"
          @click="dialogFormVisible = false"
        >
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
